import Taro, { Component } from '@tarojs/taro'
import { View, Text, ScrollView } from '@tarojs/components'
import Header from '../../components/header'
import Menu from './menu'
import List from './list'
import './category.scss'
import * as actions from '@actions/category'
import { connect } from '@tarojs/redux'
import { getWindowHeight } from '@utils/style'

@connect(state => state.category, { ...actions })
class Category extends Taro.Component {
    config = {
        navigationBarTitleText: "分类"
    }
    state = {
        categoryId: -1,
        categoryImg: '',
        loaded: false,
        loading: false,
        prodList: [],
        menuList: []
    }
    componentDidMount() {
        this.props.dispatchCategoryMenu().then((res) => {
            const categoryId = res[0].categoryId
            const categoryImg = res[0].pic
            this.props.dispatchProdList({ categoryId: categoryId }).then((res) => {
                this.setState({
                    loaded: true,
                    categoryId: categoryId,
                    categoryImg: categoryImg,
                    prodList: res
                })
            })
        })
    }

    handleMenu = (categoryId, pic) => {
        this.setState({ loading: true }, () => {
            this.props.dispatchProdList({ categoryId: categoryId }).then((res) => {
                this.setState({
                    loaded: true,
                    categoryId: categoryId,
                    categoryImg: pic,
                    prodList: res
                })
            })
        })
    }

    render() {
        const { categoryList } = this.props
        const { categoryId, loaded, categoryImg, prodList } = this.state
        const height = getWindowHeight()
        return (
            <View className='container'>
                <Header />
                <View className='main'>
                    <Menu
                        categoryId={categoryId}
                        list={categoryList}
                        onClick={this.handleMenu} />
                    {loaded &&
                        <List list={prodList} categoryImg={categoryImg} />
                    }
                </View>
            </View>
        )
    }
}
export default Category